import 'package:flutter/services.dart';

/// Created by XieXin on 2020/5/28.
/// 小数精度限制
class PrecisionLimitFormatter extends TextInputFormatter {
  ///点
  static const String point = ".";

  ///两个0
  static const String doubleZero = "00";

  ///整数长度，默认长度8
  final int intLength;

  ///小数刻度，默认保留两位小数
  final int scale;

  late RegExp _exp;

  PrecisionLimitFormatter({
    this.intLength = 8,
    this.scale = 2,
  }) {
    _exp = RegExp("[0-9.]");
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    ///处理空数据
    if (newValue.text.isEmpty) return const TextEditingValue();

    ///只允许输入小数
    if (_exp.hasMatch(newValue.text)) return oldValue;

    if (newValue.text.contains(point)) {
      ///包含小数点
      ///处理第一位是小数点
      if (newValue.text.startsWith(point)) {
        int selectionIndex = newValue.selection.end;
        return TextEditingValue(
          text: "0${newValue.text}",
          selection: TextSelection.collapsed(offset: selectionIndex),
        );
      }

      List<String> values = newValue.text.split(point);

      ///处理多个小数点
      if (values.length > 2) return oldValue;

      ///前面不能为00
      if (newValue.text.startsWith(doubleZero)) return oldValue;

      ///限制整数长度
      if (values[0].length > intLength) return oldValue;

      ///限制小数刻度
      if (values[1].length > intLength) return oldValue;

      return newValue;
    } else {
      ///不包含小数点
      ///前面不能为00
      if (newValue.text.startsWith(doubleZero)) return oldValue;

      ///限制整数长度
      if (newValue.text.length > scale) return oldValue;

      return newValue;
    }
  }
}
